package com.olddriver.crm.web.controller;

import com.olddriver.crm.annotation.PermissionName;
import com.olddriver.crm.domain.Department;
import com.olddriver.crm.page.PageResult;
import com.olddriver.crm.query.QueryObject;
import com.olddriver.crm.service.IDepartmentService;
import com.olddriver.crm.util.JsonResult;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("dept")
public class DepartmentController {
    @Autowired
    private IDepartmentService departmentService;


    @RequiresPermissions("department:list")
    @PermissionName("查看部门")
    @RequestMapping("list")
    public String list() {
        return "department/list";
    }

    @RequestMapping("listAll")
    @ResponseBody
    public List<Department> listAll() {
        return departmentService.listAll();
    }

    @ResponseBody
    @RequestMapping("query")
    @RequiresPermissions("department:query")
    @PermissionName("部门列表")
    public PageResult query(QueryObject qo) {
        PageResult result = departmentService.query(qo);
        return result;
    }

    @ResponseBody
    @RequestMapping("saveOrUpdate")
    @RequiresPermissions("department:saveOrUpdate")
    @PermissionName("部门编辑")
    public JsonResult saveOrUpdate(Department department) {
        Long id = department.getId();
        try {
            if (id != null) {
                departmentService.update(department);
            } else {
                department.setState(true);
                departmentService.insert(department);
            }
            return JsonResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.faliure();
        }
    }

    @ResponseBody
    @RequestMapping("changeState")
    @RequiresPermissions("department:changeState")
    @PermissionName("部门状态变更")
    public JsonResult changeState(Boolean state, Long id) {
        try {
            departmentService.updateState(state, id);
            return JsonResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.faliure();
        }
    }
}
